/**
 * @file 轨迹WebSocket网关
 * @description 处理实时GPS数据的WebSocket连接和推送
 * @author Assistant
 * @date 2024-02-05
 */

import {
  WebSocketGateway,
  OnGatewayConnection,
  OnGatewayDisconnect,
  WebSocketServer
} from '@nestjs/websockets';
import { Server as SocketIOServer, Socket } from 'socket.io';
import { GpsLogService } from '../services/log-processor.service';
import { LoggerService } from '../../../common/services/logger.service';
import { Injectable } from '@nestjs/common';
import { GpsLogData } from '../interfaces/gps-log-data.interface';

@Injectable()
@WebSocketGateway({
  cors: {
    origin: '*',
    methods: ['GET', 'POST', 'OPTIONS'],
    credentials: false,
    allowedHeaders: ['Access-Control-Allow-Origin']
  },
  transports: ['websocket'],
  pingInterval: 10000,
  pingTimeout: 5000,
  connectTimeout: 20000,
  allowEIO3: true,
  allowUpgrades: true
})
export class TrackGateway implements OnGatewayConnection, OnGatewayDisconnect {
  /**
   * Socket.IO服务器实例
   * @description 用于向客户端广播消息和管理连接
   */
  @WebSocketServer()
  server: SocketIOServer;

  constructor(
    private readonly gpsLogService: GpsLogService,
    private readonly logger: LoggerService
  ) {}

  /**
   * 处理客户端连接
   * @param client Socket客户端实例
   * @returns void
   */
  handleConnection(client: Socket) {
    this.logger.log(`客户端连接: ${client.id}`, 'TrackGateway');
  }

  /**
   * 处理客户端断开连接
   * @param client Socket客户端实例
   * @returns void
   */
  handleDisconnect(client: Socket) {
    this.logger.log(`客户端断开连接: ${client.id}`, 'TrackGateway');
  }

  /**
   * 广播GPS位置更新
   * @param logData 已解析的GPS数据
   */
  broadcastLocation(logData: GpsLogData) {
    try {
      this.server.emit('gps_update', logData);
      this.logger.debug(
        '位置更新广播成功',
        'TrackGateway',
        { deviceId: logData.deviceId }
      );
    } catch (error) {
      this.logger.error(
        '位置广播失败',
        error instanceof Error ? error.stack : String(error),
        'TrackGateway'
      );
    }
  }
} 